package com.example.library;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.library.adapter.UserAdapter;
import com.example.library.util.BlacklistReasonManager;

import java.util.ArrayList;
import java.util.List;

public class BlacklistActivity extends AppCompatActivity implements UserAdapter.OnUserActionListener {
    private RecyclerView rvBlacklist;
    private Spinner spinnerReason, spinnerUserType;
    private Button btnBack;
    private TextView tvTitle;
    private UserAdapter adapter;
    private List<User> allUsers;
    private List<User> filteredUsers;
    private DatabaseHelper dbHelper;
    private String[] reasonOptions = {"全部", "违纪", "超时", "冒用", "其他"};
    private String[] userTypeOptions = {"全部", "学生", "管理员"};
    private String selectedReason = "全部";
    private String selectedUserType = "全部";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blacklist);

        initViews();
        setupReasonSpinner();
        setupUserTypeSpinner();
        setupListeners();
        loadBlacklistedUsers();
    }

    private void initViews() {
        rvBlacklist = findViewById(R.id.rv_blacklist);
        spinnerReason = findViewById(R.id.spinner_reason);
        spinnerUserType = findViewById(R.id.spinner_user_type);
        btnBack = findViewById(R.id.btn_back);
        tvTitle = findViewById(R.id.tv_blacklist_title);
        rvBlacklist.setLayoutManager(new LinearLayoutManager(this));
    }

    private void setupReasonSpinner() {
        ArrayAdapter<String> reasonAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, reasonOptions);
        reasonAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerReason.setAdapter(reasonAdapter);
        spinnerReason.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedReason = reasonOptions[position];
                filterUsers();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }

    private void setupUserTypeSpinner() {
        ArrayAdapter<String> userTypeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, userTypeOptions);
        userTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerUserType.setAdapter(userTypeAdapter);
        spinnerUserType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedUserType = userTypeOptions[position];
                filterUsers();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }

    private void setupListeners() {
        btnBack.setOnClickListener(v -> finish());
    }

    private void loadBlacklistedUsers() {
        dbHelper = new DatabaseHelper(this);
        allUsers = new ArrayList<>();
        filteredUsers = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query("user", null, "status = 2", null, null, null, null);
        while (cursor.moveToNext()) {
            User user = new User();
            user.setId(cursor.getInt(cursor.getColumnIndex("id")));
            user.setName(cursor.getString(cursor.getColumnIndex("name")));
            user.setStudentId(cursor.getString(cursor.getColumnIndex("studentId")));
            user.setContact(cursor.getString(cursor.getColumnIndex("contact")));
            user.setUserType(cursor.getString(cursor.getColumnIndex("userType")));
            user.setCreditScore(cursor.getInt(cursor.getColumnIndex("creditScore")));
            user.setStatus(cursor.getInt(cursor.getColumnIndex("status")));
            allUsers.add(user);
        }
        cursor.close();
        db.close();
        filteredUsers.addAll(allUsers);
        adapter = new UserAdapter(this, filteredUsers, this);
        rvBlacklist.setAdapter(adapter);
    }

    private void filterUsers() {
        filteredUsers.clear();
        for (User user : allUsers) {
            String reason = BlacklistReasonManager.getReason(this, user.getId());
            boolean matchesReason = selectedReason.equals("全部") || reason.equals(selectedReason);
            boolean matchesUserType = selectedUserType.equals("全部") || user.getUserType().equals(selectedUserType);
            if (matchesReason && matchesUserType) {
                filteredUsers.add(user);
            }
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onDisableUser(User user) {}
    @Override
    public void onEnableUser(User user) {}
    @Override
    public void onAddToBlacklist(User user) {}
    @Override
    public void onRemoveFromBlacklist(User user) {
        new AlertDialog.Builder(this)
            .setTitle("移出黑名单")
            .setMessage("确定要将 " + user.getName() + " 移出黑名单吗？")
            .setPositiveButton("确定", (dialog, which) -> {
                removeFromBlacklist(user);
            })
            .setNegativeButton("取消", null)
            .show();
    }
    private void removeFromBlacklist(User user) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        android.content.ContentValues values = new android.content.ContentValues();
        values.put("status", 1); // 移出黑名单，设置为正常状态
        int result = db.update("user", values, "id = ?", new String[]{String.valueOf(user.getId())});
        db.close();
        if (result > 0) {
            Toast.makeText(this, "已移出黑名单", Toast.LENGTH_SHORT).show();
            user.setStatus(1);
            allUsers.remove(user);
            filteredUsers.remove(user);
            adapter.notifyDataSetChanged();
        } else {
            Toast.makeText(this, "操作失败", Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    public void onViewDetails(User user) {
        String reason = BlacklistReasonManager.getReason(this, user.getId());
        new AlertDialog.Builder(this)
            .setTitle("用户详情")
            .setMessage("姓名: " + user.getName() + "\n" +
                       "学号: " + user.getStudentId() + "\n" +
                       "用户类型: " + user.getUserType() + "\n" +
                       "状态: 黑名单\n" +
                       "原因: " + (reason.isEmpty() ? "无" : reason))
            .setPositiveButton("确定", null)
            .show();
    }
} 